package com.rongshu.sendmessage.activity;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.activity.seeImages.PictureDisplayActivityTwo;
import com.rongshu.sendmessage.adapter.ImageDataAdapter;
import com.rongshu.sendmessage.adapter.MessagePingLunAdapter;
import com.rongshu.sendmessage.base.BaseActivity;
import com.rongshu.sendmessage.base.MyApplication;
import com.rongshu.sendmessage.bean.Comments;
import com.rongshu.sendmessage.bean.FileBeanTwo;
import com.rongshu.sendmessage.bean.HealthyRegimen;
import com.rongshu.sendmessage.bean.HealthyRegimenList;
import com.rongshu.sendmessage.bean.PingLun;
import com.rongshu.sendmessage.util.ClientPublicParamUtil;
import com.rongshu.sendmessage.util.DialogUtil;
import com.rongshu.sendmessage.util.IOnItemClickListener;
import com.rongshu.sendmessage.util.ObjectUtil;
import com.rongshu.sendmessage.util.ObjectUtils;
import com.rongshu.sendmessage.util.StringUtils;
import com.rongshu.sendmessage.util.ToastUtils;
import com.rongshu.sendmessage.util.httpUtil.Constant;
import com.rongshu.sendmessage.util.httpUtil.HYContent;
import com.rongshu.sendmessage.util.httpUtil.IModel;
import com.rongshu.sendmessage.util.itemDecoration.MyItemDecoration;
import com.rongshu.sendmessage.util.itemDecoration.MyItemDecoration3;
import com.rongshu.sendmessage.view.refresh.ProgressLayout;
import com.rongshu.sendmessage.view.refresh.RefreshListenerAdapter;
import com.rongshu.sendmessage.view.refresh.TwinklingRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.rongshu.sendmessage.util.httpUtil.HYContent.LA_LO_LOCATION;

public class MessageDetailActivity extends BaseActivity implements View.OnClickListener {

    private RecyclerView recycleView;
    private TextView tv_title,tv_content,tv_time,tv_juli,tv_delete;
    private LinearLayout ll_bianji;
    private RecyclerView rl_images;
    private SimpleDraweeView iv_head_image;
    private ImageDataAdapter baseDataAdapterMain;
    private MessagePingLunAdapter mPingLunAdapter;
    private List<Comments> mPingLunList;
    private String articleId;
    private TextView tv_top_location,tv_top_time,tv_top_name,tv_top_content,tv_pinglun_number,tv_pinglun_number_top;
    private TwinklingRefreshLayout list_refresh;
    private String pullType="";
    private int page=0;
    private EditText et_pinglun;
    private Button btn_pingjia;
    private String userId;
    private String userAvatarUrl;
    private String userName;
    private View noresult_view;
    private Comments comments;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext=this;
        setContentView(R.layout.activity_message_detail);
        mPingLunList=new ArrayList<>();
        articleId = getIntent().getStringExtra("articleId");
        userId= MyApplication.mSettings.getString(HYContent.UserId,"");
        userAvatarUrl= MyApplication.mSettings.getString(HYContent.AvatarUrl,"");
        userName= MyApplication.mSettings.getString(HYContent.NickName,"");
        initView();

        initData();
    }

    private String latitude,longitude;
    private void initData() {
        String laloLocation = MyApplication.mSettings.getString(LA_LO_LOCATION, "");
        if (!StringUtils.isEmpty(laloLocation)){
            String[] split = laloLocation.split(",");
            if (split.length>=2){
                latitude=split[0];
                longitude=split[1];
            }
        }
        DialogUtil.showProgress(mContext);
        Map<String, String> param = new HashMap<String, String>();
        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
        param.put("articleId", articleId);
        param.put("longitudeStr",longitude);
        param.put("latitudeStr",latitude);
            OkGo.<String>post(new HYContent().GET_FABU_Detail_URL).params(param).tag("GET_FABU_Detail_URL").
                    execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            DialogUtil.hideProgress();
                            if (pullType.equals(Constant.PULLTYPE_DOWN)) {
                                list_refresh.finishRefreshing();
                            }
                            try {
                                IModel.AjaxResult jr = new IModel.AjaxResult(response.body());
                                final int code = jr.getCode();
                                if (code>0){
                                    HealthyRegimen message = JSON.parseObject(JSON.toJSONString(jr.getData()), HealthyRegimen.class);

                                    tv_title.setText(message.getReleaseUsernick());
//                                    ImageLoader.getInstance().displayImage(message.getReleaseUserHeadPortrait(),iv_head_image);
//                                    iv_head_image.setImageURI(message.getReleaseUserHeadPortrait());
                                    DraweeController controller= Fresco.newDraweeControllerBuilder()
                                            .setUri(message.getReleaseUserHeadPortrait())
                                            .setOldController(iv_head_image.getController())
                                            .build();
                                    iv_head_image.setController(controller);
                                    tv_content.setText(message.getSmsContent());
                                   if( StringUtils.isEmpty(message.getReleaseAddress())){
                                        tv_top_location.setText("");
                                    }else{
                                        tv_top_location.setText(message.getReleaseAddress());
                                    }

                                    tv_top_content.setText(message.getSmsContent());
                                    tv_top_time.setText(message.getCreateTime());
                                    tv_time.setText(message.getReleaseTime());
                                    tv_pinglun_number.setText("全部评论（"+message.getAllCommentCount()+"）");
                                    tv_pinglun_number_top.setText(""+message.getAllCommentCount());
                                    if( StringUtils.isEmpty(message.getLookUserToReleaseUserDistance())){
                                        tv_juli.setText("");
                                    }else{
                                        tv_juli.setText(message.getLookUserToReleaseUserDistance());
                                    }

                                    if (message.getImgUrlList()==null||message.getImgUrlList().size()<=0){
                                        rl_images.setVisibility(View.GONE);
                                    }else{
                                        rl_images.setVisibility(View.VISIBLE);
                                        initImageRecycleView(rl_images,message.getImgUrlList());
                                    }
                                    mPingLunList.clear();
                                    page=0;
                                    mPingLunList.addAll(message.getCommentList());
                                    mPingLunAdapter.notifyDataSetChanged();
                                    if (mPingLunList.size()==0){
                                        noresult_view.setVisibility(View.VISIBLE);
                                        mPingLunAdapter.notifyDataSetChanged();
                                    }else{
                                        noresult_view.setVisibility(View.GONE);
                                    }
                                }else{
                                    ToastUtils.show(mContext,jr.getMsg());
                                    if (mPingLunList.size()==0){
                                        noresult_view.setVisibility(View.VISIBLE);
                                        mPingLunAdapter.notifyDataSetChanged();
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                if (mPingLunList.size()==0){
                                    noresult_view.setVisibility(View.VISIBLE);
                                    mPingLunAdapter.notifyDataSetChanged();
                                }
                            }

                        }

                        @Override
                        public void onError(Response<String> response) {
                            DialogUtil.hideProgress();
                            if (mPingLunList.size()==0){
                                noresult_view.setVisibility(View.VISIBLE);
                                mPingLunAdapter.notifyDataSetChanged();
                            }
                            if (pullType.equals(Constant.PULLTYPE_DOWN)) {
                                list_refresh.finishRefreshing();
                            }
                        }
                    });
        tv_delete.setOnClickListener(this);
    }
    //初始化图片的recycleView
    private void initImageRecycleView(RecyclerView rl_images,List<FileBeanTwo>images) {
        int screenWidth = ObjectUtil.getScreenWidth(mContext);
        int itemWidth = (screenWidth - ObjectUtil.dip2px(mContext, (16 + 12 + 40 + 12 + 10))) / 3;
        GridLayoutManager layoutmanager;
        if (images.size()==4||images.size()==2){
            layoutmanager = new GridLayoutManager(mContext, 2);
            LinearLayout.LayoutParams  layoutManager = (LinearLayout.LayoutParams) rl_images.getLayoutParams();
            layoutManager.rightMargin= itemWidth;
        }else{
            LinearLayout.LayoutParams  layoutManager = (LinearLayout.LayoutParams) rl_images.getLayoutParams();
            layoutManager.rightMargin=0;
            layoutmanager = new GridLayoutManager(mContext, 3);
        }
        if (rl_images.getItemDecorationCount()<=0){
            rl_images.addItemDecoration(new MyItemDecoration(10,10));
        }
        layoutmanager.setOrientation(GridLayoutManager.VERTICAL);
        //设置RecyclerView 布局管理器
        rl_images.setLayoutManager(layoutmanager);
        //设置设置RecyclerView的适配器Adapter
        List<String> list=new ArrayList<>();
        for (int i = 0; i < images.size(); i++) {
            list.add(images.get(i).getImgUrl());
        }
        baseDataAdapterMain = new ImageDataAdapter(list);
        rl_images.setAdapter(baseDataAdapterMain);
        ArrayList<String> newList=new ArrayList<>(list);
        baseDataAdapterMain.setOnItemClickListener(new ImageDataAdapter.OnItemClickListener() {
            @Override
            public void onLongClick(int position) {

            }
            @Override
            public void onClick(int p) {
                //查看图片，
                ArrayList<String> list =  newList;
                String path= list.get(p);
                Intent intent = new Intent(mContext, PictureDisplayActivityTwo.class);
                intent.putExtra("img_url",path+"");
                intent.putExtra("index",p);
                intent.putExtra("isCanDelete",false);
                try {
                    intent.putStringArrayListExtra("uris", list);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mContext.startActivity(intent);
            }
        });
    }
    private void initView() {
        TextView title = findViewById(R.id.title);
        title.setText("信息详情");
        LinearLayout titleLayLeft = findViewById(R.id.titleLayLeft);
        titleLayLeft.setOnClickListener(view->finish());
        tv_title=findViewById(R.id.tv_title);

        tv_top_location=findViewById(R.id.tv_top_location);
        et_pinglun=findViewById(R.id.et_pinglun);
        btn_pingjia=findViewById(R.id.btn_pingjia);
        btn_pingjia.setText("评论");
        tv_top_time=findViewById(R.id.tv_top_time);
        tv_top_name=findViewById(R.id.tv_top_name);
        tv_top_content=findViewById(R.id.tv_top_content);
        tv_content=findViewById(R.id.tv_content);
        tv_pinglun_number=findViewById(R.id.tv_pinglun_number);
        tv_pinglun_number_top=findViewById(R.id.tv_pinglun_number_top);
        tv_time=findViewById(R.id.tv_time);
        tv_juli=findViewById(R.id.tv_juli);
        tv_delete=findViewById(R.id.tv_delete);
        iv_head_image=findViewById(R.id.iv_head_image);
        rl_images=findViewById(R.id.rl_images);
        ll_bianji=findViewById(R.id.ll_bianji);
        recycleView=findViewById(R.id.recycleView);
        noresult_view=findViewById(R.id.noresult_view);
        initRecycleView();
        list_refresh = findViewById(R.id.list_refresh);
        ProgressLayout headerView = new ProgressLayout(mContext);
        list_refresh.setHeaderView(headerView);
        list_refresh.setOverScrollRefreshShow(false);
        list_refresh.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                pullType = Constant.PULLTYPE_DOWN;
                initData();
            }

            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
                page++;
                pullType = Constant.PULLTYPE_UP;

                getMorePingLun();
            }
        });
    }
//去评论
    private void getMorePingLun() {
        DialogUtil.showProgress(mContext);
        Map<String, String> param = new HashMap<String, String>();
        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
        param.put("page", page+"");
        param.put("articleId", articleId);
        //
        OkGo.<String>post(new HYContent().PINGLUN_MORE_URL).params(param).tag("PINGLUN_MORE_URL").
                execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        list_refresh.finishLoadmore();
                        try {
                            IModel.AjaxResult jr = new IModel.AjaxResult(response.body());
                            final int code = jr.getCode();
                            if (code>0){
                                List<Comments> messageLists = JSON.parseArray(JSON.toJSONString(jr.getJSONArrayData()), Comments.class);
                                mPingLunList.addAll(messageLists);
                                mPingLunAdapter.setmList(messageLists);
                                mPingLunAdapter.notifyDataSetChanged();
                            }else{
                                ToastUtils.show(mContext,jr.getMsg());
                            }
                            DialogUtil.hideProgress();
                        } catch (Exception e) {
                            e.printStackTrace();
                            DialogUtil.hideProgress();
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtil.hideProgress();
                        if (pullType.equals(Constant.PULLTYPE_DOWN)) {
                            list_refresh.finishRefreshing();
                        } else {
                            list_refresh.finishLoadmore();
                        }
                    }
                });
    }

    private void initRecycleView() {
        recycleView.setHasFixedSize(true);//设置固定大小
        recycleView.setItemAnimator(new DefaultItemAnimator());//设置默认动画
        recycleView.addItemDecoration(new MyItemDecoration());
        recycleView.addItemDecoration(new MyItemDecoration(0, 0));
        GridLayoutManager mLayoutManage = new GridLayoutManager(mContext, 1);
        recycleView.setLayoutManager(mLayoutManage);
        mPingLunAdapter = new MessagePingLunAdapter(
                mContext,
                R.layout.pinglun_item,
                mPingLunList,
                new IOnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                //recycleview的点击事件
                comments = mPingLunList.get(position);
                String commentUserNick = comments.getCommentUserNick();
                et_pinglun.setHint("回复"+commentUserNick+":");
                et_pinglun.setFocusable(true);
                btn_pingjia.setText("回复");
                ObjectUtils.showKeyboard(et_pinglun);
//                et_pinglun.setFocusable(true);
//
//                et_pinglun.setFocusableInTouchMode(true);

            }
        });
        recycleView.setAdapter(mPingLunAdapter);
    }

//    private void initRecycleData() {
//        mPingLunList.clear();
//        PingLun pinglun=new PingLun("http://img.mp.itc.cn/upload/20170808/5861bc790e654d56bc9289c567b44875_th.jpg",
//                "同事张三","很棒想你学习，一起加油哦！","4小时前");
//        mPingLunList.add(pinglun);ad
//        PingLun pinglun1=new PingLun("http://img.mp.itc.cn/upload/20170808/5861bc790e654d56bc9289c567b44875_th.jpg",
//                "同事王五","看了这么多晒单就属看到你的最有感触，期待一起工作一起学习！加油",
//                "1天前");
//        mPingLunList.add(pinglun1);
//        PingLun pinglun2=new PingLun("http://img.mp.itc.cn/upload/20170808/5861bc790e654d56bc9289c567b44875_th.jpg",
//                "同事张三","很棒想你学习，一起加油哦！","5天前");
//        mPingLunList.add(pinglun2);
//        PingLun pinglun3=new PingLun("http://img.mp.itc.cn/upload/20170808/5861bc790e654d56bc9289c567b44875_th.jpg",
//                "同事王五","看了这么多晒单就属看到你的最有感触，期待一起工作一起学习！加油。",
//                "10天前");
//        mPingLunList.add(pinglun3);
//        mPingLunAdapter.notifyDataSetChanged();
//
//    }
    private void goPingJia(Map<String, String> param){
        DialogUtil.showProgress(mContext);
        OkGo.<String>post(new HYContent().SEND_PINGJIA_URL).params(param).tag("SEND_PINGJIA_URL").
                execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtil.hideProgress();
                        try {
                            IModel.AjaxResult jr = new IModel.AjaxResult(response.body());
                            final int code = jr.getCode();
                            if (code>0){
                                if (comments!=null){
                                    comments=null;
                                }
                                et_pinglun.setText("");
                                btn_pingjia.setText("评论");
                                et_pinglun.setHint("请输入你的内容");
                                ObjectUtils.hideKeyboard(et_pinglun);
                                MyApplication.editor.putBoolean(HYContent.IS_EDIT,true);
                                MyApplication.editor.commit();
                                HealthyRegimen message = JSON.parseObject(JSON.toJSONString(jr.getData()), HealthyRegimen.class);
                                initData();
                            }else{
                                ToastUtils.show(mContext,jr.getMsg());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtil.hideProgress();
                        if (pullType.equals(Constant.PULLTYPE_DOWN)) {
                            list_refresh.finishRefreshing();
                        }
                    }
                });
        tv_delete.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.tv_delete){
            ToastUtils.show(mContext,"删除开发中");
        }else if (v.getId()==R.id.btn_pingjia){
            if (StringUtils.isEmpty(et_pinglun.getText())){
                ToastUtils.show(mContext,"请先输入评论内容哦");
                return;
            }
            Map<String, String> param = new HashMap<>();
            param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
            param.put("articleId", articleId);//信息id

            param.put("commentUserId",userId);//回复信息的用户id
            param.put("commentUserNick",userName);// 回复信息的用户昵称
            param.put("commentUserAvatarUrl",userAvatarUrl);// 回复信息的用户头像地址
            if (comments!=null){
                param.put("toCommentMsgId",comments.getCommentUserId());//  被评论信息的id
                param.put("commentContent", "回复"+comments.getCommentUserNick()+":"+et_pinglun.getText().toString());//回复内容：
            }else {
                param.put("commentContent", et_pinglun.getText().toString());//回复内容：
            }

            goPingJia(param);
        }else {
            if ("评论".equals(btn_pingjia.getText().toString())){
                return;
            }
            et_pinglun.setText("");
            btn_pingjia.setText("评论");
            et_pinglun.setHint("请输入你的内容");
            ObjectUtils.hideKeyboard(et_pinglun);
        }
    }
}